<template>
    <div class="wrapper">
        <div :style="{position:'relative'}">
            <div class="coruverImage">
                <img src="http://pm0tnn81a.bkt.clouddn.com/defaultShopCover.jpg" alt=""
                     ref="coruverImage"
                >
            </div>
            <div class="upload-btn">
                <input type="file" class="fileinput" @change="fileChange"
                ></input>
                更换背景
            </div>
        </div>
    </div>
</template>
<script>
    import {uploadImage} from "./service";
    import MyAlert from '../../../utils/myalert'
    import {isImage} from "../../../utils/dom";

    export default {
        props: {
            onFileChange: {
                type: Function,
                default: () => {
                }
            }
        },
        methods: {
            preview(file) {
                if (isImage(file)) {
                    var self = this
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        self.$refs['coruverImage'].src = e.target.result
                    }
                    reader.readAsDataURL(file);
                }
            },
            fileChange(e) {
                var self = this
                /*询问 旧文件将会被覆盖，确定上传？*/
                MyAlert.confirm("旧文件将会被覆盖，确定上传？").then(() => {
                    self.preview(e.target.files[0])
                    MyAlert.loading()
                    uploadImage(e.target.files).then(res => {
                        MyAlert.clear()
                        MyAlert.success("上传成功")
                        console.log(res.url());
                        self.$props.onFileChange(res)
                    }).catch(e => {
                        setTimeout(() => {
                            MyAlert.clear()
                        }, 500)
                        MyAlert.fail(e.message)
                    })
                })

            }
        }
    }
</script>
<style lang="less" scoped>
    .wrapper {
        margin-bottom: 20px;
        .coruverImage {
            height: px2rem(80*2);
            img {
                height: 100%;
                width: 100%;
            }
        }
        .upload-btn {
            position: absolute;
            border: 1px solid orangered;
            padding: 3px;
            font-size: 12px;
            border-radius: 0 0 5px 5px;
            color: orangered;
            background: #fff;
            bottom: -20px;
            left: px2rem(300);
            .fileinput {
                width: 80%;
                font-size: 100%;
                position: absolute;
                opacity: 0;
            }
        }
    }
</style>